package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryList() {
        String listKey="cache:shopType:"+"list";
        // 1. 从redis查询缓存
        String shopTypeKey = stringRedisTemplate.opsForValue().get(listKey);
        // 2. 查询得到直接返回
        if (StrUtil.isNotBlank(shopTypeKey)){
            List<ShopType> shopTypes = JSONUtil.toList(shopTypeKey, ShopType.class);
            return Result.ok(shopTypes);
        }
        // 3. 查询不到查询数据库
        List<ShopType> typeList = query().orderByAsc("sort").list();

        // 4. 不存在返回错误
        if (typeList.size()==0){
            return Result.fail("无数据");
        }

        // 5. 存入redis中
        stringRedisTemplate.opsForValue().set(listKey,JSONUtil.toJsonStr(typeList));
        // 6. 返回数据list
        return Result.ok(typeList);
    }
}
